package com.luo.backend.repository;

import com.luo.backend.entity.GroupBuyingParticipant;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 团购参与者仓储接口
 */
@Repository
public interface GroupBuyingParticipantRepository extends JpaRepository<GroupBuyingParticipant, Long> {
    
    /**
     * 根据活动ID查找参与者列表
     */
    List<GroupBuyingParticipant> findByActivityIdOrderByJoinedAtAsc(Long activityId);
    
    /**
     * 根据活动ID和用户ID查找参与记录
     */
    Optional<GroupBuyingParticipant> findByActivityIdAndUserId(Long activityId, Long userId);
    
    /**
     * 根据活动ID和用户ID查找参与记录（排除已取消的）
     */
    @Query("SELECT p FROM GroupBuyingParticipant p WHERE p.activityId = :activityId AND p.userId = :userId AND p.status != 'cancelled'")
    Optional<GroupBuyingParticipant> findActiveParticipantByActivityIdAndUserId(@Param("activityId") Long activityId, @Param("userId") Long userId);
    
    /**
     * 根据用户ID查找参与的团购活动
     */
    @Query("SELECT p FROM GroupBuyingParticipant p WHERE p.userId = :userId ORDER BY p.joinedAt DESC")
    Page<GroupBuyingParticipant> findByUserId(@Param("userId") Long userId, Pageable pageable);
    
    /**
     * 统计活动的参与人数
     */
    @Query("SELECT COUNT(p) FROM GroupBuyingParticipant p WHERE p.activityId = :activityId AND p.status != 'cancelled'")
    Long countActiveParticipantsByActivityId(@Param("activityId") Long activityId);
    
    /**
     * 根据活动ID删除参与记录
     */
    void deleteByActivityId(Long activityId);
    
    /**
     * 根据订单ID查找参与记录
     */
    Optional<GroupBuyingParticipant> findByOrderId(Long orderId);
    
    /**
     * 统计用户参与的拼单次数
     */
    long countByUserId(Long userId);
}

